/**
 * Project Name:wuservice-spring-boot-starter
 * File Name:DruidDataSourceAutoConfiguration.java
 * Package Name:com.wu.common.config
 * Date:2017年2月23日上午11:46:21
 * Copyright (c) 2017, worldunion All Rights Reserved.
 *
 */

package com.dz.mybatis;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.dz.db.IdGenerator;
import com.dz.db.impl.IdGeneratorImpl;

/**
 * ClassName: DruidDataSourceAutoConfiguration <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON(可选). <br/>
 * date: 2017年2月23日 上午11:46:21 <br/>
 *
 * @author yexx
 * @version
 * 
 */
@Configuration
@EnableConfigurationProperties({ DruidDataSourceProperties.class, DataSourceProperties.class })
@ConditionalOnClass(DruidDataSource.class)
public class DruidDataSourceAutoConfiguration {

	@Autowired
	private DruidDataSourceProperties properties;

	@Autowired
	private DataSourceProperties dataSourceProperties;

	@Bean(initMethod = "init", destroyMethod = "close")
	public DruidDataSource dataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUrl(dataSourceProperties.getUrl());
		dataSource.setUsername(dataSourceProperties.getUsername());
		dataSource.setPassword(dataSourceProperties.getPassword());
		dataSource.setMinIdle(properties.getMinIdle());
		dataSource.setInitialSize(properties.getInitialSize());
		dataSource.setMaxActive(properties.getMaxActive());
		dataSource.setValidationQuery(properties.getValidationQuery());
		return dataSource;
	}

	@Bean
	public PlatformTransactionManager txManager(DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}
	
	@Bean
	public IdGenerator idGenerator(JdbcTemplate jdbcTemplate){
		return new IdGeneratorImpl(jdbcTemplate);
	}
}
